#include "head_s.h"

int upload(user_t* status, portocol_t* portocol, int socket_fd)
{
    int file_name_len = 0;
    int ret_len = recv(socket_fd, &file_name_len, sizeof(int), 0);
    if(ret_len == -1){
        perror("recv filename_len failed!\n");
        exit(1);
    }
    char file_name[60] = {0};
    int ret = recv(socket_fd, file_name, sizeof(file_name), 0);
    if(ret == -1){
        perror("recv filename failed!\n");
        exit(1);
    }
    char* last_path = strrchr(file_name, '/');
    if(last_path != NULL){
        *last_path = '\0';
        mkdir(file_name, 0600);
        *last_path = '/';

    }

    int file_len = 0;
    ret_len = recv(socket_fd, &file_len, sizeof(int), MSG_WAITALL);
    if(ret_len == -1){
        perror("recv file failed!\n");
        exit(1);
    }
    int file_fd = open(file_name, O_RDWR | O_CREAT, 0600);
    if(file_fd == -1){
        perror("open failed!\n");
        exit(1);
    }
    ftruncate(file_fd, file_len);
    void* p = mmap(NULL, file_len, PROT_READ | PROT_WRITE, MAP_SHARED, file_fd, 0);
    ret = recv(socket_fd, p, file_len, MSG_WAITALL);
    munmap(p, file_len);

    close(file_fd);
    close(socket_fd);

    return 0;
}

